package com.ctjsoft.eureka;

import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.ServerCodecs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.Arrays;

/**
 * Eureka 服务注册配置
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/8/26 14:20
 */
@Configuration
public class EurekaRegisterConfig {

    @Autowired
    private EurekaServerConfig eurekaServerConfig;

    @Autowired
    private EurekaClientConfig eurekaClientConfig;

    @Autowired
    @Qualifier(value = "eurekaClient")
    private EurekaClient eurekaClient;

    @Value("${eureka.server.defaultOpenForTrafficCount:1}")
    private int defaultOpenForTrafficCount;

    /**
     * Eureka 注册中心允许注册的 IP 白名单地址，配置时使用逗号隔开。
     * 默认为空数组，如果为空，则表示不进行限制，只有不为空时，才只允许指定 IP 进行注册.
     */
    @Value("${eureka.server.allowed.address:}")
    private String[] allowedAddress;

    @Primary
    @Bean
    public PeerAwareInstanceRegistry myPeerAwareInstanceRegistry(ServerCodecs serverCodecs) {
        System.out.println("===============================================================");
        System.out.println("===============================================================");
        System.out.println("===============================================================");
        System.out.println("============= IP Address White List: " + Arrays.asList(allowedAddress));
        System.out.println("===============================================================");
        System.out.println("===============================================================");
        System.out.println("===============================================================");
        return new EurekaInstanceRegistry(
                this.eurekaServerConfig,
                this.eurekaClientConfig,
                serverCodecs,
                this.eurekaClient,
                this.defaultOpenForTrafficCount,
                Arrays.asList(allowedAddress)
        );
    }

}